﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
//using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using ThreeByte.ActiveDeck.Config;
using System.Xml.Linq;
using ThreeByte.Media;
using log4net;
using System.IO;
using ThreeByte.Controls;
using ThreeByte.ActiveDeck.AddIn.Content.Controls;

namespace ThreeByte.ActiveDeck.Content
{
    /// <summary>
    /// Interaction logic for UserSlidePreview.xaml
    /// </summary>
    public partial class UserSlidePreview : UserControl, IPreviewControl
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(UserSlidePreview));

        private UserSlideConfig _config;

        public PageConfig Config { get; set; }

        public UserSlidePreview(UserSlideConfig config) {
            InitializeComponent();
            _config = config;
            Config = config;
            DataContext = config;
        }

        public PresentationPageConfiguration GetPageConfiguration() {
            XNamespace ns = Service.ServiceConfiguration.NAMESPACE;

            PresentationPageConfiguration newPage = new PresentationPageConfiguration();

            XElement pageNode = _config.GetPresentationXml("UserSlide");
            
            //If ZoomEnabled, just use the image as uploaded
            GraphicResource res = _config.Image;
            if(!(_config.ZoomEnabled)) {
                this.UpdateLayout();
                res = new GraphicResource(ImageUtil.SaveToBitmapSource(LayoutRoot, ImageUtil.DefaultPortraitSize), null, ImageType.JPEG);
            }
            if(_config.NavigateForward || _config.NavigateBackward) {
                pageNode.Add(new XAttribute("NavigateForward", _config.NavigateForward));
                pageNode.Add(new XAttribute("NavigateBackward", _config.NavigateBackward));
            }
            
            if(res != null) {
                newPage.Resources[res.ID] = res;
                XElement imageNode = new XElement(ns + "Image", new XAttribute("ResourceID", res.ID));
                if(_config.ZoomEnabled) {
                    imageNode.Add(new XAttribute("ZoomEnabled", _config.ZoomEnabled));
                }
                imageNode.Add(new XAttribute("Orientation", _config.LayoutOrientation));
                pageNode.Add(imageNode);
            }

            newPage.ConfigXml = pageNode;
            return newPage;
        }

        private void LayoutRoot_DragEnter(object sender, DragEventArgs e) {
            log.Debug("Drag Enter");
            e.Effects = DragDropEffects.All;
        }

        private void LayoutRoot_DragLeave(object sender, DragEventArgs e) {

        }

        private void LayoutRoot_DragOver(object sender, DragEventArgs e) {
            //log.Debug("Drag Over");
            e.Effects = DragDropEffects.All;
        }

        private void LayoutRoot_Drop(object sender, DragEventArgs e) {
            log.Debug("Drop");

            try {
                string[] formats = e.Data.GetFormats();
                int i = 0;
                foreach(string s in formats) {
                    log.DebugFormat("Format [{0}]: {1}", i++, s);
                }

                //If FileDrop is exposed, then look at the extension
                if(formats.Any(p => (p == DataFormats.FileDrop))) {
                    string path = ((string[])(e.Data.GetData(DataFormats.FileDrop)))[0];
                    string extension = System.IO.Path.GetExtension(path).ToLower();

                    if(extension == @".png"
                        || extension == @".jpg"
                        || extension == @".jpeg") { // Try to parse as an image
                        //Parse as an image
                        LoadNewImage(path);
                    } else {
                        log.InfoFormat("Unrecognized file format: {0}", extension);

                    }

                } else if(formats.Any(p => (p == @"PowerPoint 14.0 Slides Package"))) {
                    //Embedded PNG

                    //Return Active Slide Range
                    Microsoft.Office.Interop.PowerPoint.SlideRange slideRange = Globals.ThisAddIn.Application.ActiveWindow.Selection.SlideRange;
                    log.DebugFormat("Slide Count: {0} ID:{1} Index:{2} ", slideRange.Count, slideRange.SlideID, slideRange.SlideIndex);
                    _config.Image = new GraphicResource(SlideUtil.Snapshot(slideRange), "DragDrop_Snapshot", ImageType.JPEG);
                }

                //log.Info("Inspect:" + o);
                //log.InfoFormat("Properties DPI:{0}, Width:{1}, Decode:{2}", newBitmap.DpiX, newBitmap.PixelWidth, newBitmap.DecodePixelWidth);

            } catch(Exception ex) {
                log.Fatal("Collossal Fail", ex);
            }
        }

        private void LoadNewImage(MemoryStream memStream) {
            BitmapImage newBitmap = new BitmapImage();
            newBitmap.BeginInit();
            newBitmap.CacheOption = BitmapCacheOption.OnLoad;
            newBitmap.StreamSource = memStream;
            newBitmap.EndInit();
            newBitmap.Freeze();
            _config.Image = new GraphicResource(newBitmap, "DragDrop", ImageType.JPEG);
        }

        private void LoadNewImage(string path) {
            using(FileStream fs = new FileStream(path, FileMode.Open)) {
                BitmapImage newBitmap = new BitmapImage();
                newBitmap.BeginInit();
                newBitmap.CacheOption = BitmapCacheOption.OnLoad;
                newBitmap.StreamSource = fs;
                newBitmap.EndInit();
                newBitmap.Freeze();
                _config.Image = new GraphicResource(newBitmap, "DragDrop", ImageType.JPEG);
            }
        }
    }
}
